<template>
  <div class="searchbox-container">
    <h2 class="title">搜索</h2>
    <div class="searchbox">
      <img src="../../../assets/icons/svg/psy-search.svg" class="search-icon" />
      <input
        type="text"
        placeholder="输入你想搜索的内容"
        class="search-input"
        v-model="searchQuery"
        @input="handleInput"
        @keyup.enter="search"
      />
      <img
        src="../../../assets/icons/svg/psy-clear.svg"
        class="clear-icon"
        v-if="showClearIcon"
        @click="clearSearch"
      />
    </div>
  </div>
  <div class="body">
    <template v-if="showRecentlyView">
      <RecentlyViews></RecentlyViews>
    </template>
    <template v-else>
      <searchResult @back="handleBackEvent"></searchResult>
    </template>
  </div>
</template>

<script setup>
import { ref } from "vue";

import RecentlyViews from "./components/RecentLyViews.vue";
import searchResult from "./components/SearchResult.vue";

const searchQuery = ref("");
const showClearIcon = ref(false);
const showRecentlyView = ref(true);
// 当输入框的内容发生变化时调用
const handleInput = (event) => {
  const target = event.target;
  showClearIcon.value = target.value.trim() !== "";
};

const clearSearch = () => {
  searchQuery.value = "";
  showClearIcon.value = false;
};

const search = () => {
  const searchText = searchQuery.value;
  console.log(`搜索内容: ${searchText}`);
  showRecentlyView.value = false;
};

const handleBackEvent = (param) => {
  showRecentlyView.value = param;
};
</script>

<style scoped>
.searchbox-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}

.searchbox {
  position: relative;
  display: block;
  margin-top: 10px;
}

.search-icon {
  position: absolute;
  top: 50%;
  left: 10px;
  cursor: pointer;
  transform: translateY(-50%);
}

.clear-icon {
  position: absolute;
  top: 50%;
  right: 10px;
  cursor: pointer;
  transform: translateY(-50%);
}

.search-input {
  width: auto;
  padding: 10px 40px;
  font-size: 16px;
  border: 2px solid #ccc;
  border-radius: 20px;
}

.body {
  display: flex;
  flex-direction: column;
  padding: 10px;
}

.title {
  margin-top: 20px;
  font-size: 20px;
  text-align: center;
}
</style>
